﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TopShooter.Editor
{
	public partial class GetString : Form
	{
		private bool _isActive;
        private bool _isEnterDown;
		static public string LastCommand { get; set; }

		private Action<String> _applyMethod;

		static public string GetCommand()
		{
            Game.IsPaused = true;
			GetString win = new GetString(null);
			win.ShowDialog();
            Game.IsPaused = false;
			return GetString.LastCommand ?? "";
		}

		public GetString(Action<string> applyMethod)
		{
			InitializeComponent();
			_applyMethod = applyMethod;
			txtCommand.KeyUp += new KeyEventHandler(txtCommand_KeyUp);
            txtCommand.KeyDown += new KeyEventHandler(txtCommand_KeyDown);
		}

        void txtCommand_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (_isEnterDown == false)
                    _isEnterDown = true;
                //Apply();
            }
            else if (e.KeyCode == Keys.Escape)
            {
                LastCommand = "";
                this.Close();
            }
        }
		void txtCommand_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
                if (_isEnterDown == true)
                {
                    _isEnterDown = false;
                    Apply();
                }
			}
		}
		protected override void OnShown(EventArgs e)
		{
			_isActive = true;
			base.OnShown(e);
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			_isActive = false;
			base.OnClosing(e);
		}
		private void btnEnter_Click(object sender, EventArgs e)
		{
			Apply();
		}

		private void Apply()
		{
			_isActive = false;
			this.Close();

			if (_applyMethod != null)
				_applyMethod(LastCommand);
		}

		private void txtCommand_TextChanged(object sender, EventArgs e)
		{
			if (_isActive)
			{
				LastCommand = txtCommand.Text;
			}
			else
			{
				txtCommand.Text = LastCommand;
			}
		}


    }
}
